#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"

void Inittree(PH* php)
{
	php->a = NULL;
	php->capacity = 0;
	php->size = 0;
}

void destroy(PH* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void swap(PhDataType* parent, PhDataType*child)
{
	PhDataType t=0;
	t = *parent;
	*parent = *child;
	*child = t;
}

void AdjustUp(PhDataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[parent] < a[child])
		{
			swap(&a[parent],&a[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
			break;
	}
}

void push(PH* php,PhDataType x)
{
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		PhDataType* tmp = (PhDataType*)realloc(php->a, newcapacity * sizeof(PhDataType));
		if (tmp == NULL)
		{
			perror("realloc");
			return;
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	php->size++;
	AdjustUp(php->a, php->size -1);
}

void AdjustDown(PhDataType *a,PhDataType parent,int n)
{
	PhDataType child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] < a[child])
		{
			child++;
		}
		if (a[parent] > a[child])
		{
			swap(&a[parent],&a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}

void pop(PH* php)
{
	assert(php);
	swap(&php->a[0],&php->a[php->size-1]);
	php->size--;
	AdjustDown(php->a, 0,php->size); 

}

PhDataType Phtop(PH* php)
{
	assert(php);
	assert(php->size > 0);
	return php->a[0];
}

bool PhEmpty(PH* php)
{
	assert(php);
	return php->size == 0;
}